﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace Publicuse.Util
{
    /// <summary>
    /// HttpClient请求工具类
    /// </summary>
    public static class HttpClientUtil
    {
        /// <summary>
        /// 同步GET请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="msg"></param>
        /// <param name="headers"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static string HttpGet(string url, out string msg, Dictionary<string, string> headers = null, int timeout = 0)
        {
            msg = string.Empty;
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    //取消Expect协议头
                    client.DefaultRequestHeaders.ExpectContinue = false;
                    if (headers != null)
                    {
                        foreach (KeyValuePair<string, string> header in headers)
                        {
                            client.DefaultRequestHeaders.Add(header.Key, header.Value);
                        }
                    }

                    if (timeout > 0)
                    {
                        client.Timeout = new TimeSpan(0, 0, timeout);
                    }

                    Byte[] resultBytes = client.GetByteArrayAsync(url).Result;
                    return Encoding.UTF8.GetString(resultBytes);
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return string.Empty;
            }
        }

        /// <summary>
        /// 异步GET请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="headers"></param>
        /// <param name="timeout"></param>
        /// <returns></returns>
        public static async Task<string> HttpGetAsync(string url, Dictionary<string, string> headers = null,
            int timeout = 0)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    //取消Expect协议头
                    client.DefaultRequestHeaders.ExpectContinue = false;
                    if (headers != null)
                    {
                        foreach (KeyValuePair<string, string> header in headers)
                        {
                            client.DefaultRequestHeaders.Add(header.Key, header.Value);
                        }
                    }

                    if (timeout > 0)
                    {
                        client.Timeout = new TimeSpan(0, 0, timeout);
                    }

                    Byte[] resultBytes = await client.GetByteArrayAsync(url);
                    return Encoding.Default.GetString(resultBytes);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 同步POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="msg"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <param name="timeout"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string HttpPost(string url, string postData, out string msg, Dictionary<string, string> headers = null,
            string contentType = null, int timeout = 0, Encoding encoding = null)
        {
            msg = string.Empty;
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    //取消Expect协议头
                    client.DefaultRequestHeaders.ExpectContinue = false;
                    if (headers != null)
                    {
                        foreach (KeyValuePair<string, string> header in headers)
                        {
                            client.DefaultRequestHeaders.Add(header.Key, header.Value);
                        }
                    }

                    if (timeout > 0)
                    {
                        client.Timeout = new TimeSpan(0, 0, timeout);
                    }

                    using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
                    {
                        if (contentType != null)
                        {
                            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(contentType);
                        }

                        using (HttpResponseMessage responseMessage = client.PostAsync(url, content).Result)
                        {
                            Byte[] resultBytes = responseMessage.Content.ReadAsByteArrayAsync().Result;
                            return Encoding.UTF8.GetString(resultBytes);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return null;
            }
        }

        /// <summary>
        /// 异步POST请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <param name="headers"></param>
        /// <param name="contentType"></param>
        /// <param name="timeout"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static async Task<string> HttpPostAsync(string url, string postData, string mediaType, string charset,
            Dictionary<string, string> headers = null, string contentType = null, int timeout = 0,
            Encoding encoding = null)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    //取消Expect协议头
                    client.DefaultRequestHeaders.ExpectContinue = false;
                    if (headers != null)
                    {
                        foreach (KeyValuePair<string, string> header in headers)
                        {
                            var newKey = HttpUtility.UrlEncode(header.Key);
                            string pattern = "[\u4e00-\u9fbb]";
                            if (Regex.IsMatch(header.Value, pattern))
                            {
                                var newValue = HttpUtility.UrlEncode(header.Value);
                                client.DefaultRequestHeaders.Add(newKey, newValue);
                            }
                            else
                            {
                                client.DefaultRequestHeaders.Add(newKey, header.Value);
                            }
                        }
                    }

                    if (timeout > 0)
                    {
                        client.Timeout = new TimeSpan(0, 0, timeout);
                    }
                    using (HttpContent content = new StringContent(postData ?? "", encoding ?? Encoding.UTF8))
                    {
                        content.Headers.ContentType = new MediaTypeHeaderValue(mediaType);
                        //content.Headers.TryAddWithoutValidation("Content-MD5", contentMD5);
                        content.Headers.ContentType.CharSet = charset;
                        using (HttpResponseMessage responseMessage = await client.PostAsync(url, content))
                        {
                            Byte[] resultBytes = await responseMessage.Content.ReadAsByteArrayAsync();
                            return Encoding.UTF8.GetString(resultBytes);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }
}
